package com.woniu113.junk.order.consumer;


import com.woniu113.junk.order.service.OrderInfoService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 检查支付发起后是否支付成功
 * */
@Component
public class CheckPayConsumer {
    @Resource
    private OrderInfoService orderInfoService;

    private static final int MAX_CHECK_COUNT = 3; // 最多检查3次
    private static final long CHECK_INTERVAL = 120000; // 每2分钟检查一次（以毫秒为单位）

    @RabbitListener(queues = "order_check_queue")
    public void handleOrderCheck(String orderNum) throws Exception {
        for (int currentCount = 1; currentCount <= MAX_CHECK_COUNT; currentCount++) {
            System.out.println("自检订单 ID: " + orderNum + ", 当前检查次数: " + currentCount);
            // 调用自检方法
            boolean isPending = orderInfoService.orderCheck(orderNum);
            if (!isPending) {
                // 自检通过，订单支付成功，退出循环
                System.out.println("订单 ID: " + orderNum + " 支付成功，停止自检。");
                return;
            }
            // 自检未通过，等待下一次检查
            if (currentCount < MAX_CHECK_COUNT) {
                System.out.println("订单 ID: " + orderNum + " 支付未成功，等待下一次自检...");
                try {
                    Thread.sleep(CHECK_INTERVAL); // 等待2分钟再进行下一次检查
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    // 记录异常情况
                    System.err.println("自检线程被中断: " + e.getMessage());
                    return;
                }
            }
        }
        // 三次自检均未通过，调用补偿代码
        System.out.println("订单 ID: " + orderNum + " 三次自检均未通过，调用补偿逻辑。");
        //调用补偿逻辑
        orderInfoService.updateOrder(orderNum);
    }
}
